package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.EcnomicInventory;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.mapper.SignAdminMapper;
import net.yunxinyong.sign.service.AssignTasksService;
import net.yunxinyong.sign.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class AssignTasksImpl implements AssignTasksService {
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private SignAdminMapper signAdminMapper;
    @Autowired
    private RecordService recordService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public void AssignTasksToCunsus(List<Long> idList, Integer censusTakerId ,Integer type,Integer managerId) {
        //int size = idList.size();
        //判断权限，普查员不可修改
        if (signAdminMapper.selectByPrimaryKey(managerId).getRole().equals("普查员")){
            throw new CECException(505,"没有操作权限");
        }
        boolean b = true;
        if(type == 1){
            for (Long id : idList){
                if(id != null){
                    EcnomicInventory ecnomicInventory = new EcnomicInventory();
                    ecnomicInventory.setId(id);
                    ecnomicInventory.setAdminId(censusTakerId);
                    b = ecnomicInventoryMapper.updateByPrimaryKeySelective(ecnomicInventory) > 0;
                }
            }
            //取出前端传过来的需要添加企业的数量，并把数量放在企业id的位置，后面操作记录的时候再删除
            boolean insert = recordService.insert(managerId, null, censusTakerId, 10);
            if(! b || !insert){
                throw new CECException(505,"分配企业失败");
            }
        }else if (type == 2){
            for(Long id : idList){
                if(id != null){
                    EcnomicInventory ecnomicInventory = new EcnomicInventory();
                    ecnomicInventory.setId(id);
                    ecnomicInventory.setAdminId(0);
                    b = ecnomicInventoryMapper.updateByPrimaryKeySelective(ecnomicInventory) > 0;
                }
            }
            //取出前端传过来的需要删除企业的数量，并把数量放在企业id的位置，后面操作记录的时候再删除
            boolean update = recordService.insert(managerId,null,censusTakerId,11);
            if(! b || !update){
                throw new CECException(505,"普查员减少企业失败");
            }
        }
    }
}
